package com.centaline.androidsalesblog.fragments.listmap;

import android.content.Intent;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.widget.ZoomControls;

import com.android.volley.VolleyError;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.navi.BaiduMapNavigation;
import com.baidu.mapapi.navi.NaviParaOption;
import com.baidu.mapapi.utils.OpenClientUtil;
import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.activities.WebActivity;
import com.centaline.androidsalesblog.adapter.StoreAgentAdapter;
import com.centaline.androidsalesblog.api.sale.StoreMapApi;
import com.centaline.androidsalesblog.base.BaseFragment;
import com.centaline.androidsalesblog.constants.AppConstant;
import com.centaline.androidsalesblog.constants.ExtraConstant;
import com.centaline.androidsalesblog.iml.BaiduMarkerClick;
import com.centaline.androidsalesblog.model.businissobject.StoreBo;
import com.centaline.androidsalesblog.model.databaseobject.StaffDo;
import com.centaline.androidsalesblog.model.responseobject.StoreListRo;
import com.centaline.androidsalesblog.overlay.StoreOverlay;
import com.centaline.androidsalesblog.utils.ContactUtil;
import com.centanet.framework.glide.GlideLoad;
import com.centanet.framework.interfaces.IResponseListener;
import com.centanet.framework.widget.CProgressDialog;

import java.util.ArrayList;
import java.util.Locale;

/**
 * 门店地图详情
 * Created by Lihq on 2016/2/18.
 */
public class StoreMapFragment extends BaseFragment implements View.OnClickListener, BaiduMap.OnMapClickListener, BaiduMap.OnMapStatusChangeListener {

    private MapView mapView;
    private BaiduMap baiduMap;
    protected CProgressDialog loadingDialog;

    private LocationClient locationClient;
    private BitmapDescriptor mCurrentMarker;
    public MyLocationListenner myListener = new MyLocationListenner();
    private MyLocationConfiguration.LocationMode mCurrentMode;
    protected MapStatus endMapStatus;
    private LatLng latLng, estLatLng;
    private boolean isFirstLoc = true; // 是否首次定位
    protected ArrayList<StoreBo> storeBos = new ArrayList<>();
    private ArrayList<StaffDo> staffDos = new ArrayList<>();
    private StoreAgentAdapter storeAgentAdapter;
    protected int targetScreenY;//中心点

    private StoreOverlay storeOverlay;
    private Overlay overlay;
    private double mLat;
    private double mLng;

    private LinearLayout ll_store_pop;
    private RelativeLayout rl_btn_circle, rl_btn_location;
    private AppCompatTextView atv_store_title, atv_store_address, atv_agent_count;
    private ImageView img_360;
    private RecyclerView mRecyclerview_horizontal;
    private RelativeLayout rl_store_nav, rl_store_consult;
    private StoreMapApi storeMapApi;
    private int mapStatesTag = 0;//地图变化标志 0.请求数据 1.地图上升 2.不做逻辑
    private boolean isStoreClick = false;


    @Override
    protected int setLayoutId() {
        return R.layout.fragment_store_map;
    }

    @Override
    protected void findViews(View view) {
        mapView = (MapView) view.findViewById(R.id.mapView);
        ll_store_pop = (LinearLayout) view.findViewById(R.id.ll_store_pop);
        atv_store_title = (AppCompatTextView) view.findViewById(R.id.atv_store_title);
        atv_agent_count = (AppCompatTextView) view.findViewById(R.id.atv_agent_count);
        atv_store_address = (AppCompatTextView) view.findViewById(R.id.atv_store_address);
        mRecyclerview_horizontal = (RecyclerView) view.findViewById(R.id.mRecyclerview_horizontal);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
        mRecyclerview_horizontal.setLayoutManager(layoutManager);
        rl_store_nav = (RelativeLayout) view.findViewById(R.id.rl_store_nav);
        rl_store_consult = (RelativeLayout) view.findViewById(R.id.rl_store_consult);
        rl_btn_circle = (RelativeLayout) view.findViewById(R.id.rl_btn_circle);
        rl_btn_location = (RelativeLayout) view.findViewById(R.id.rl_btn_location);
        img_360 = (ImageView)view.findViewById(R.id.img_360);
    }

    @Override
    protected void initView() {
        baiduMap = mapView.getMap();
        // 隐藏logo
        View child = mapView.getChildAt(1);
        if (child != null && (child instanceof ImageView || child instanceof ZoomControls)) {
            child.setVisibility(View.INVISIBLE);
        }
        //地图上比例尺
        mapView.showScaleControl(false);
        // 隐藏缩放控件
        mapView.showZoomControls(false);

        mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;
        baiduMap
                .setMyLocationConfigeration(new MyLocationConfiguration(
                        mCurrentMode, true, mCurrentMarker));
        baiduMap.setMyLocationEnabled(true);
        baiduMap.setOnMapClickListener(this);
        baiduMap.setOnMapStatusChangeListener(this);
        rl_btn_circle.setOnClickListener(this);
        rl_btn_location.setOnClickListener(this);
        locationClient = new LocationClient(getActivity());
        locationClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setIsNeedAddress(true);
        option.setScanSpan(1000);
        locationClient.setLocOption(option);
        locationClient.start();

        storeAgentAdapter = new StoreAgentAdapter(getContext(), GlideLoad.initRound(this), staffDos);
        mRecyclerview_horizontal.setAdapter(storeAgentAdapter);

        storeMapApi = new StoreMapApi(getClass(), StoreListRo.class,
                new IResponseListener<StoreListRo>() {
                    @Override
                    public void onResponse(StoreListRo storeListRo) {
                        storeBos.clear();
                        if (storeListRo.getList() != null) {
                            storeBos.addAll(storeListRo.getList());
                        }
                        storeOverlay.removeFromMap();
                        storeOverlay.setData(storeBos);
                        storeOverlay.addToMap();
                        cancelLoadingDialog();
                    }

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        cancelLoadingDialog();
                        netWorkUnable();
                    }
                });

        storeOverlay = new StoreOverlay(getActivity(), baiduMap, new BaiduMarkerClick() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                if (overlay != null)
                    overlay.remove();
                final StoreBo storeBo = marker.getExtraInfo().getParcelable(ExtraConstant.MAP_EXTRA_INFO);
                atv_store_title.setText(storeBo.getStoreName());
                atv_store_address.setText(storeBo.getStoreAddr());
                img_360.setVisibility(!TextUtils.isEmpty(storeBo.getTencentVistaUrl())? View.VISIBLE : View.GONE);
                estLatLng = new LatLng(storeBo.getLpt_Y(), storeBo.getLpt_X());
                mapStatesTag = 1;
                baiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLng(marker.getPosition()));
                OverlayOptions overlayOptions = new MarkerOptions()
                        .position(new LatLng(storeBo.getLpt_Y(), storeBo.getLpt_X()))
                        .icon(BitmapDescriptorFactory
                                .fromResource(R.drawable.ic_store_point_selected));
                overlay = baiduMap.addOverlay(overlayOptions);

                atv_agent_count.setText(String.format(Locale.CHINA, "共%d位经纪人为您提供帮助", storeBo.getAgentNum()));
                staffDos.clear();
                staffDos.addAll(storeBo.getStaffDos());
                storeAgentAdapter.notifyDataSetChanged();
                img_360.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        getActivity().startActivity(new Intent(getActivity(), WebActivity.class)
                                .putExtra(ExtraConstant.WebUrl, storeBo.getTencentVistaUrl()));
                    }
                });
                rl_store_consult.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ContactUtil.dial(getActivity(), storeBo.getStoreTel());
                        baiduEvent("K1_4_Click");
                    }
                });

                rl_store_nav.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        navigate();
                    }
                });
                ll_store_pop.setVisibility(View.VISIBLE);
                return false;
            }
        });
        baiduMap.setOnMarkerClickListener(storeOverlay);
    }


    @Override
    public void onMapClick(LatLng latLng) {
        ll_store_pop.setVisibility(View.GONE);
        if (overlay != null)
            overlay.remove();
        if (isStoreClick) {
            isStoreClick = false;
            mapStatesTag = 2;
            baiduMap.animateMapStatus(MapStatusUpdateFactory.scrollBy(0,
                    -targetScreenY / 2), 150);
        }
        baiduMap.getUiSettings().setZoomGesturesEnabled(true);
    }

    @Override
    public boolean onMapPoiClick(MapPoi mapPoi) {
        return false;
    }


    @Override
    public void onMapStatusChangeStart(MapStatus mapStatus) {

    }

    @Override
    public void onMapStatusChange(MapStatus mapStatus) {

    }

    @Override
    public void onMapStatusChangeFinish(MapStatus mapStatus) {
        if (targetScreenY == 0) {
            targetScreenY = mapStatus.targetScreen.y;
        }
        switch (mapStatesTag) {
            case 0:
                if (AppConstant.NearbyEnable){
                    if (mapStatus.zoom>14.0f){
                        showLoadingDialog();
                        requestEsfList(mapStatus);
                    }
                }
                mapStatesTag = 0;
                break;
            case 1:
                baiduMap.animateMapStatus(MapStatusUpdateFactory.scrollBy(0,
                        targetScreenY / 2), 150);

                mapStatesTag = 2;
                isStoreClick = true;
                break;
            case 2:
                mapStatesTag = 0;
                break;
            default:
                break;
        }
    }

    /**
     * 请求门店列表
     */

    protected void requestEsfList(MapStatus mapStatus) {
        endMapStatus = mapStatus;
        storeMapApi.setSouthwest(mapStatus.bound.southwest);
        storeMapApi.setNortheast(mapStatus.bound.northeast);
        storeMapApi.startRequest();
    }

    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mapView == null) {
                return;
            }
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    .latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            baiduMap.setMyLocationData(locData);
            mLat = location.getLatitude();
            mLng = location.getLongitude();
            if (isFirstLoc) {
                if (!AppConstant.NearbyEnable) {
                    cancelLoadingDialog();
                }
                isFirstLoc = false;
                mLat = location.getLatitude();
                mLng = location.getLongitude();
                latLng = new LatLng(mLat, mLng);
                LatLng ll = new LatLng(location.getLatitude(),
                        location.getLongitude());
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll).zoom(17f);
                baiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
            }
        }

        public void onReceivePoi(BDLocation poiLocation) {

        }
    }


    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onDestroy() {
        // 退出时销毁定位
        locationClient.stop();
        // 关闭定位图层
        baiduMap.setMyLocationEnabled(false);
        mapView.onDestroy();
        mapView = null;
        super.onDestroy();
    }

    @Override
    public void onPause() {
        mapView.onPause();
        super.onPause();
    }

    @Override
    public void onResume() {
        mapView.onResume();
        super.onResume();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_btn_location:
                if (isStoreClick)
                    mapStatesTag = 1;
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(new LatLng(mLat, mLng)).zoom(17.0f);
                baiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                break;
            case R.id.rl_btn_circle:

                break;
        }
    }


    /**
     * 导航
     */
    private void navigate() {
        if (latLng == null) {
            Toast.makeText(getActivity(), "未获取当前位置", Toast.LENGTH_SHORT)
                    .show();
        } else {
            NaviParaOption para = new NaviParaOption();
            para.startPoint(latLng).endPoint(estLatLng);
            if (OpenClientUtil.getBaiduMapVersion(getActivity()) == 0) {
                BaiduMapNavigation.openWebBaiduMapNavi(para, getActivity());
            } else {
                BaiduMapNavigation.openBaiduMapNavi(para, getActivity());
            }
        }
    }
}

